package com.ljx.rabbit.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ljx.rabbit.context.BaseContext;
import com.ljx.rabbit.domain.dto.LoginForm;
import com.ljx.rabbit.domain.po.User;
import com.ljx.rabbit.domain.po.UserLikes;
import com.ljx.rabbit.domain.vo.UserVo;
import com.ljx.rabbit.properties.JwtProperty;
import com.ljx.rabbit.result.R;
import com.ljx.rabbit.service.IUserService;
import com.ljx.rabbit.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2025-01-21
 */
@RestController
@CrossOrigin
@Slf4j
@Api(tags = "用户管理")
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
    private final IUserService userService;
    private final JwtProperty jwtProperty;

    @PostMapping("/login")
    @ApiOperation(value = "登录")
    public R<UserVo> login(@RequestBody LoginForm loginForm) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getAccount, loginForm.getAccount())
                .eq(User::getPassword, loginForm.getPassword());
        User user = userService.getOne(wrapper);
        if (user == null) {
            return R.error("用户不存在");
        }
        if (!user.getPassword().equals(loginForm.getPassword())) {
            return R.error("密码错误");
        }
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String token = JwtUtil.createJWT(jwtProperty.getSecret(), jwtProperty.getExpire(), claims);
        userVo.setToken(token);
        log.info("id:{} 的用户登录成功，token:{}",userVo.getId(), token);
        return R.success(userVo);
    }

    @ApiOperation(value = "获取用户信息")
    @GetMapping("/info")
    public R<User> info() {
        User user = userService.getById(BaseContext.getCurrentId());
        return R.success(user);
    }

    @ApiOperation(value = "获取用户点赞信息")
    @GetMapping("/likes")
    public R<List<UserLikes>> getUserLikes(){
        List<UserLikes> userLikes = userService.getUserLikes();
        return R.success(userLikes);
    }
}
